﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DLL
{
    public class Service
    {
        public static ZhongchouDBEntities db = new ZhongchouDBEntities();
        private static List<Userinfo> userinfos = new List<Userinfo>();
        private static List<Projectinfo> projectinfos = new List<Projectinfo>();
        private static List<Returnsetinfo> returnsetinfos = new List<Returnsetinfo>();
        private static List<Launchinfo> launchinfos = new List<Launchinfo>();
        private static List<CollectionInfo> collectionInfos = new List<CollectionInfo>();
        private static List<Addressinfo> addressinfos = new List<Addressinfo>();


        private static List<ProjectinfoDTO> ProjectAllList = new List<ProjectinfoDTO>();
        private static List<ProjectinfoDTO> ProjectReadyList = new List<ProjectinfoDTO>();
        private static List<ProjectinfoDTO> ProjectCompleteList = new List<ProjectinfoDTO>();
        private static List<ProjectinfoDTO> ProjectNOList = new List<ProjectinfoDTO>();
        private static List<ProjectinfoDTO> projectALLList = new List<ProjectinfoDTO>();
        //辉
        private static List<ProjectinfoDTO> xhxm = new List<ProjectinfoDTO>();
        private static List<CollectionInfo> collecfos = new List<CollectionInfo>();
        private static UserinfoDTO Unanem;
        private static List<int> WXHDXMid = new List<int>();
        private static List<int> zcxmid = new List<int>();




        public static int GetProjectNums(int i)
        {
            switch (i)
            {
                case 1:
                    return db.Database.SqlQuery<int>("select COUNT(projectid) from Projectinfo").First();
                case 2:
                    return db.Database.SqlQuery<int>("select COUNT(projectid) from Projectinfo where state='众筹中'").First();
                case 3:
                    return db.Database.SqlQuery<int>("select COUNT(projectid) from Projectinfo where state='已完成'").First();
                default:
                    return 0;
            }
            
        }
        

            private static ProjectinfoDTO GetProjectDTO(Projectinfo item)
        {
            int pro;
            if (0 == (int)(((double)(item.incomemoney % item.targetmoney) / item.targetmoney) * 100))
            {
                if (item.incomemoney == 0)
                {
                    pro = 0;
                }
                else
                {
                    pro = 100;
                }
            }
            else
            {
                pro = (int)(((double)(item.incomemoney % item.targetmoney) / item.targetmoney) * 100);
            }
            return new ProjectinfoDTO()
            {
                projectid = item.projectid,
                projectname = item.projectname,
                imageurl = item.imageurl,
                time = item.time,
                targetmoney = item.targetmoney,
                collection = item.collection,
                remainingday = ((DateTime)item.createdate).AddDays(item.time).Day - DateTime.Now.Day * -1,
                incomemoney = item.incomemoney,
                progress = pro,
                state = item.state,
                CreaData = (DateTime)item.createdate,
                EndData = ((DateTime)item.createdate).AddDays(item.time)
            };
        }




        #region 辉功能方法
        /// <summary>
        /// 发起用户的项目查询
        /// </summary>
        /// <param name="i"></param>
        /// <param name="userid"></param>
        /// <returns></returns>
        public static List<ProjectinfoDTO> GetProjectAllList(int i, int uind)
        {
            ProjectAllList.Clear();
            ProjectReadyList.Clear();
            ProjectCompleteList.Clear();
            ProjectNOList.Clear();
            string sql = $"select * from Projectinfo where userid={uind}";
            var dada = db.Database.SqlQuery<Projectinfo>(sql);
            foreach (var item in dada)
            {
                if ("众筹中".Equals(item.state))
                {
                    ProjectReadyList.Add(GetProjectDTO(item));

                }
                if ("已完成".Equals(item.state))
                {
                    ProjectCompleteList.Add(GetProjectDTO(item));
                }
                if ("已失败".Equals(item.state))
                {
                    ProjectNOList.Add(GetProjectDTO(item));
                }
                else
                {
                    ProjectAllList.Add(GetProjectDTO(item));
                }
            }
            switch (i)
            {
                case 1:
                    return ProjectAllList;
                case 2:
                    return ProjectReadyList;
                case 3:
                    return ProjectCompleteList;
                case 4:
                    return ProjectNOList;
                default:
                    break;
            }
            return ProjectAllList;
        }

        /// <summary>
        /// 用户喜欢的项目id和支持项目的id
        /// </summary>
        /// <param name="i"></param>
        /// <param name="uinid"></param>
        /// <returns></returns>
        public static List<int> Buinid(int uinid, int op)
        {
            int a;
            List<int> xmid = new List<int>();
            if (op == 1)
            {
                string sql = $"select * from CollectionInfo where userid='{uinid}'and supportmoney =0";
                var result = db.Database.SqlQuery<CollectionInfo>(sql);
                foreach (var item in result)
                {
                        //取喜欢项目的id
                        xmid.Add(item.projectid);
                    a = item.projectid;
                }

            }
            else if (op == 2)
            {
                string sql = $"select * from CollectionInfo where userid='{uinid}'and supportmoney >0";
                var result = db.Database.SqlQuery<CollectionInfo>(sql);
                foreach (var item in result)
                {
                    //取项支持目的id
                    xmid.Add(item.projectid);
                }
            }

            return xmid;
        }

        /// <summary>
        /// 根据喜欢项目id取出喜欢项目
        /// </summary>
        /// <param name="ia"></param>
        /// <param name="uind"></param>
        /// <returns></returns>
        public static List<ProjectinfoDTO> GetProjectAllList(string ia, int uind)
        {
            WXHDXMid.Clear();
            ProjectAllList.Clear();
            WXHDXMid = Buinid(uind, 1);
            projectinfos = db.Projectinfo.ToList();
            foreach (var item in projectinfos)
            {
                for (int i = 0; i < WXHDXMid.Count; i++)
                {
                    if (WXHDXMid[i] == item.projectid)
                    {
                        if ("待审核".Equals(item.state) || "草稿".Equals(item.state))
                        {
                            break;
                        }
                        else
                        {
                            ProjectAllList.Add(GetProjectDTO(item));
                        };

                    };
                };

            };
            return ProjectAllList;
        }

        /// <summary>
        /// 根据支持项目id取出支持的项目
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        public static List<ProjectinfoDTO> GetProjectAllList(string ia, int uind, string add)
        {
            zcxmid.Clear();
            zcxmid = Buinid(uind, 2);
            ProjectAllList.Clear();
            projectinfos = db.Projectinfo.ToList();
            foreach (var item in projectinfos)
            {
                for (int i = 0; i < zcxmid.Count; i++)
                {
                    if (zcxmid[i] == item.projectid)
                    {
                        if ("待审核".Equals(item.state) || "草稿".Equals(item.state))
                        {
                            break;
                        }
                        else
                        {
                            ProjectAllList.Add(GetProjectDTO(item));
                        };

                    };
                };

            };
            return ProjectAllList;
        }

        /// <summary>
        /// 根据用户id取出用户信息
        /// </summary>
        /// <param name="usid"></param>
        /// <returns></returns>
        public static UserinfoDTO GetProjectBllList(int usid)
        {

            string sql1 = $"select * from Userinfo where userid={usid}";
            var result1 = db.Database.SqlQuery<Userinfo>(sql1);
            foreach (var item in result1)
            {
                Unanem = new UserinfoDTO
                {
                    usernikename = item.usernikename,//用户名
                    registertime = item.registertime,//注册时间
                    imgurl = item.imgurl,//用户头像
                    userdesc = item.userdesc,//个人说明
                    address = item.address,//所在地
                    userphone = item.userphone,//电话号码
                };

            }
            return Unanem;
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="usid"></param>
        /// <param name="po"></param>
        /// <returns></returns>
        public static bool update(string fileName, int usid, int po)
        {

            string sql = $"update Userinfo set imgurl='../images/{po}{fileName}' where userid={usid}";
            var lsl = db.Database.ExecuteSqlCommand(sql);
            if (lsl > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 删除项目
        /// </summary>
        /// <param name="pjid"></param>
        public static bool delet(string pjid)
        {
            string sql = $"delete from Projectinfo where projectid={pjid}";
            int ad = db.Database.ExecuteSqlCommand(sql);
            if (ad == 1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        #endregion










        /// <summary>
        /// 传入数据源进行分页
        /// </summary>
        /// <param name="data">输入数据源</param>
        /// <returns>分页完成后的数据，分页总数</returns>
        public static (SortedDictionary<int, List<ProjectinfoDTO>> 数据源,int 分页总数) GetProjectListByIndex(List<ProjectinfoDTO> data)
        {
            //分页数组  为了数据绑定
            List<int> Index_Num = new List<int>();
            Index_Num.Clear();
            //分割后的数据
            SortedDictionary<int, List<ProjectinfoDTO>> 分割后的总数据源 = new SortedDictionary<int, List<ProjectinfoDTO>>();
            分割后的总数据源.Clear();
            //中间临时存储数据
            List<ProjectinfoDTO> TempIndexItem = null;
            //获取分页后的余数  最后一页不足4页的情况 yushu!=0
            int yushu = data.Count() % 4;
            //获取有多少个分页  以4个为1页
            if (data.Count() % 4 == 0)//是否能分完
            {
                //往分页数组内加入分页数 为了数据展示，分页数组第一个元素+1
                for (int j = 0; j < data.Count() / 4; j++)
                {
                    Index_Num.Add(j + 1);
                }
            }
            else
            {
                //往分页数组内加入分页数 为了数据展示，分页数组第一个元素+1
                for (int j = 0; j < data.Count() / 4; j++)
                {
                    Index_Num.Add(j + 1);
                }
                //因为有余数  还要加最后一页
                Index_Num.Add((data.Count() / 4) + 1);
            }
            Console.WriteLine("分页数：" + Index_Num.Count());
            int max = 0;
            int min = 0;
            int num = 1;
            int temp = 0;
            for (; num <= Index_Num.Count();)
            {
                TempIndexItem = new List<ProjectinfoDTO>();
                max = num * 4;
                min = max - 4;
                for (; min < max; min++)
                {
                    try
                    {
                        TempIndexItem.Add(data[min]);
                    }
                    catch (Exception)
                    {
                        if (yushu != 0)
                        {
                            TempIndexItem.Clear();
                            int j = data.Count() - yushu;
                            for (int i = 0; i < yushu; i++)
                            {
                                TempIndexItem.Add(data[j]);
                                j++;
                            }
                        }
                        break;
                    }
                }
                分割后的总数据源.Add(temp, TempIndexItem);
                num++;
                temp++;
            };
            return (分割后的总数据源,Index_Num.Count());
        }




        /// <summary>
        /// 根据类型和项目状态返回是否排序的数据
        /// </summary>
        /// <param name="type">"全部"&{类型},项目类型</param>
        /// <param name="i">1全部2众筹中3已完成 项目状态</param>
        /// <param name="paixu">""默认排序 "收藏"收藏升序 "进度"进度升序 排序</param>
        /// <param name="sousuo">""默认不查询&{搜索词} 查询</param>
        /// <returns>返回对应数据</returns>
        public static List<ProjectinfoDTO> GetProjectListByTypeStatePaixu(string type, int state, string paixu,string sousuo)
        {
            List<ProjectinfoDTO> dTOs = new List<ProjectinfoDTO>();
            if (type=="全部")
            {
                type = "1 = '1'";
            }
            else
            {
                type = $"type = '{type}'";
            }
            string statee = "";
            switch (state)
            {
                case 1:
                    statee = "and 2=2 and state<>'已失败' and state<>'草稿' and state <> '待审核'";
                    break;
                case 2:
                    statee = "and state='众筹中'";
                    break;
                case 3:
                    statee = "and state='已完成'";
                    break;
                default:
                    break;
            }
            string pai = "";
            switch (paixu)
            {
                case "":
                    pai = $"and 3=3";
                    break;
                case "收藏":
                    pai = "order by collection desc";
                    break;
                case "进度":
                    pai = "and 3=3";
                    break;
                default:
                    break;
            }
            string likeChaXun = "";
            if ("".Equals(sousuo))
            {
                likeChaXun = "and 4=4";
            }
            else
            {
                likeChaXun = $"and projectname like'%{sousuo}%'";
            }
            string sql = $"select * from Projectinfo where {type} {statee} {likeChaXun} {pai}";
            var date = db.Database.SqlQuery<Projectinfo>(sql);
            foreach (var item in date)
            {
                dTOs.Add(GetProjectDTO(item));
            }
            if (paixu=="进度")
            {
                return NewSortList(dTOs);
            }
            else
            {
                return dTOs;
            }
            
        }

        /// <summary>
        /// 获取进度排序后的方法
        /// </summary>
        /// <param name="dTOs">源数据</param>
        /// <returns></returns>
        private static List<ProjectinfoDTO> NewSortList(List<ProjectinfoDTO> dTOs)
        {
            List<ProjectinfoDTO> newProjectinfoDTOs = new List<ProjectinfoDTO>();
            var studer = dTOs.OrderBy( stt =>  stt.progress);
            foreach (var item in studer)
            {
                newProjectinfoDTOs.Add(item);
            }
            return newProjectinfoDTOs;
        }


















        public static List<ProjectinfoDTO> GetProjectAllList(int i)
        {
            ProjectAllList.Clear();
            ProjectReadyList.Clear();
            ProjectCompleteList.Clear();
            projectinfos = db.Projectinfo.ToList();
            foreach (var item in projectinfos)
            {
                if ("众筹中".Equals(item.state))
                {
                    ProjectReadyList.Add(GetProjectDTO(item));
                    ProjectAllList.Add(GetProjectDTO(item));
                }
                else if ("已成功".Equals(item.state))
                {
                    ProjectCompleteList.Add(GetProjectDTO(item));
                    ProjectAllList.Add(GetProjectDTO(item));
                }
            }
            switch (i)
            {
                case 1:
                    return ProjectAllList;
                case 2:
                    return ProjectReadyList;
                case 3:
                    return ProjectCompleteList;
                default:
                    break;
            }
            return ProjectAllList;
        }
        /// <summary>
        /// 获取Userinfo数据源
        /// </summary>
        /// <param name="u">Userinfo类</param>
        /// <returns>返回对应数组</returns>
        public static List<Userinfo> GetDataSource(Userinfo u)
        {
            try
            {
                userinfos.Clear();
                var UserDate = db.Userinfo.ToList();
                foreach (var item in UserDate)
                {
                    userinfos.Add(GetUser(item));
                }
                return userinfos;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
        }

        /// <summary>
        /// 获取Projectinfo数据源
        /// </summary>
        /// <param name="p">Projectinfo类</param>
        /// <returns>返回对应数组</returns>
        public static List<Projectinfo> GetDataSource(Projectinfo p)
        {
            try
            {
                projectinfos.Clear();
                var ProjectDate = db.Projectinfo.ToList();
                foreach (var item in ProjectDate)
                {
                    projectinfos.Add(GetProject(item));
                }
                return projectinfos;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
        }

        /// <summary>
        /// 获取Returnsetinfo数据源
        /// </summary>
        /// <param name="r">Returnsetinfo类</param>
        /// <returns>返回对应数组</returns>
        public static List<Returnsetinfo> GetDataSource(Returnsetinfo r)
        {
            try
            {
                returnsetinfos.Clear();
                var ReturnseDate = db.Returnsetinfo.ToList();
                foreach (var item in ReturnseDate)
                {
                    returnsetinfos.Add(GetReturnse(item));
                }
                return returnsetinfos;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
        }

        /// <summary>
        /// 获取Launchinfo数据源
        /// </summary>
        /// <param name="l">Launchinfo类</param>
        /// <returns>返回对应数组</returns>
        public static List<Launchinfo> GetDataSource(Launchinfo l)
        {
            try
            {
                launchinfos.Clear();
                var LaunchDate = db.Launchinfo.ToList();
                foreach (var item in LaunchDate)
                {
                    launchinfos.Add(GetLaunch(item));
                }
                return launchinfos;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
        }

        /// <summary>
        /// 获取CollectionInfo数据源
        /// </summary>
        /// <param name="c">CollectionInfo类</param>
        /// <returns>返回对应数组</returns>
        public static List<CollectionInfo> GetDataSource(CollectionInfo c)
        {
            try
            {
                collectionInfos.Clear();
                var CollectionDate = db.CollectionInfo.ToList();
                foreach (var item in CollectionDate)
                {
                    collectionInfos.Add(GetCollection(item));
                }
                return collectionInfos;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
        }

        /// <summary>
        /// 获取Addressinfo数据源
        /// </summary>
        /// <param name="a">Addressinfo类</param>
        /// <returns>返回对应数组</returns>
        public static List<Addressinfo> GetDataSource(Addressinfo a)
        {
            try
            {
                addressinfos.Clear();
                var data = db.Addressinfo.ToList();
                foreach (var item in data)
                {
                    addressinfos.Add(GetAddress(item));
                }
                return addressinfos;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
        }


        /// <summary>
        /// 增删改
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <returns>返回操作是否成功</returns>
        public static bool EXEXE(string sql)
        {
            try
            {
                var sss = db.Database.ExecuteSqlCommand(sql);
                db.SaveChanges();
                return sss > 0;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
        }



        private static Addressinfo GetAddress(Addressinfo item)
        {
            return new Addressinfo()
            {
                address = item.address,
                addresscity = item.addresscity,
                addressid = item.addressid,
                postcode = item.postcode,
                userid = item.userid,
                username = item.username,
                userphone = item.userphone
            };
        }

        private static CollectionInfo GetCollection(CollectionInfo item)
        {
            return new CollectionInfo()
            {
                collectionid = item.collectionid,
                projectid = item.projectid,
                supportmoney = item.supportmoney,
                userid = item.userid
            };
        }

        private static Launchinfo GetLaunch(Launchinfo item)
        {
            return new Launchinfo()
            {
                projectid = item.projectid,
                accountname = item.accountname,
                address = item.address,
                bankname = item.bankname,
                banknumber = item.banknumber,
                launchid = item.launchid,
                launchname = item.launchname,
                phone = item.phone,
                subbranch = item.subbranch
            };
        }

        private static Returnsetinfo GetReturnse(Returnsetinfo item)
        {
            return new Returnsetinfo()
            {
                freight = item.freight,
                number = item.number,
                projectid = item.projectid,
                returncontent = item.returncontent,
                returnid = item.returnid,
                supportmoney = item.supportmoney,
                time = item.time
            };
        }

        private static Projectinfo GetProject(Projectinfo item)
        {
            return new Projectinfo()
            {
                aboutus = item.aboutus,
                collection = item.collection,
                createdate = item.createdate,
                imageurl = item.imageurl,
                incomemoney = item.incomemoney,
                need = item.need,
                other = item.other,
                projectadd = item.projectadd,
                projectdesc = item.projectdesc,
                projectid = item.projectid,
                projectlabel = item.projectlabel,
                projectname = item.projectname,
                promise = item.promise,
                risk = item.risk,
                showimgurl = item.showimgurl,
                state = item.state,
                targetmoney = item.targetmoney,
                time = item.time,
                type = item.type,
                userid = item.userid,
                videourl = item.videourl,
                wanttodo = item.wanttodo
            };
        }

        private static Userinfo GetUser(Userinfo item)
        {
            return new Userinfo()
            {
                address = item.address,
                imgurl = item.imgurl,
                registertime = item.registertime,
                sex = item.sex,
                userdesc = item.userdesc,
                userid = item.userid,
                usernikename = item.usernikename,
                userphone = item.userphone,
                userpwd = item.userpwd,
                userstate = item.userstate,
                website = item.website
            };
        }
    }
}


